<template>
  <div>
    <common-head title="购物车"/>
    <div class="wrap">
      <div class="items">
        <van-swipe-cell v-for="(item, index) in items" :key="item.id">
          <div class="item">
            <van-checkbox @click="changeStatu(index) " v-model="item.selected"/>
            <van-card
              :num="item.number"
              :price="item.price"
              :title="item.name"
              :thumb="item.pic"
            >
            <template #footer>
              <van-stepper @change="changeNum(index)" v-model="item.number" />
            </template>
            </van-card>
            </div>
            <template #right>
              <van-button
                @click="deleteCart(item.key)"
                square text="删除"
                type="danger"
                class="delete-button"
              />
            </template>
        </van-swipe-cell>
      </div>
      <van-submit-bar :price="total*100" button-text="确认订单" @submit="onSubmit">
        <van-checkbox v-model="allChecked">全选</van-checkbox>
      </van-submit-bar>
    </div>
     <common-tab/>
  </div>
</template>

<script>
import { fetchCartItems, addNum, changeChecked, deleteCart } from 'api'
import { getToken } from 'utils'
import { Dialog } from 'vant'
import CommonHead from '../../components/CommonHead.vue'
import CommonTab from '../../components/CommonTab.vue'
export default {
  components: { CommonHead, CommonTab },
  name: 'cart',
  data () {
    return {
      items: [],
      total: 0
    }
  },
  created () {
    this.fetchCartItems()
  },
  watch: {
    items () {
      // 监听购物车数据，将数据存储到vuex中
      this.$store.commit('cart/set_items', this.items)
    }
  },
  methods: {
    // 商品删除
    deleteCart (key) {
      Dialog.confirm({
        title: '删除商品',
        message: '宝，您真的要删除吗'
      })
        .then(() => {
          deleteCart({
            key,
            token: getToken()
          }).then(res => {
            if (res.data.code === 0) {
              this.items = res.data.data.items
              this.total = res.data.data.price
            }
            if (res.data.code === 700) {
              this.items = []
              this.total = 0
            }
          })
        })
    },
    // 复选框状态改变
    changeStatu (index) {
      const { key, selected } = this.items[index]
      changeChecked({
        key,
        selected,
        token: getToken()
      }).then(res => {
        if (res.data.code === 0) {
          this.items = res.data.data.items
          this.total = res.data.data.price
        }
      })
    },
    changeNum (index) { // 商品数量的加减
      const { key, number } = this.items[index]
      addNum({
        key,
        number,
        token: getToken()
      }).then(res => {
        if (res.data.code === 0) {
          this.items = res.data.data.items
          this.total = res.data.data.price
        }
      })
    },
    onSubmit () {
      // 提交订单
      this.$router.replace('/comfirmOrder')
    },
    // 请求购物车数据
    fetchCartItems () {
      fetchCartItems({
        token: getToken()
      }).then(res => {
        if (res.data.code === 0) {
          this.items = res.data.data.items
          this.total = res.data.data.price
        }
      })
    }
  },
  computed: { // 全选和复选框利用计算属性，依赖
    allChecked: {
      get () {
        // 利用三目 如果购物车里数据的length为0，就将全选改为false,如果不为0，就利用every判断当前的复选框是否全部为false或者是true，将全选绑定复选框，只有有一个复选框没有选中，结果都为false
        return this.items.length === 0 ? false : this.items.every(item => item.selected)
      },
      set (val) {
        // val指的是当前全选的状态，布尔值
        // 定义一个空数组
        const keys = []
        // 遍历当前购物车里的数据，放进新数组里
        this.items.forEach((item) => {
          keys.push(item.key)
        })
        // 在接口里面将key分割出来，传入参数
        changeChecked({
          key: keys.join(','),
          selected: val,
          token: getToken()
        }).then(res => {
          if (res.data.code === 0) {
            this.items = res.data.data.items
            this.total = res.data.data.price
          }
        })
      }
    }
  }
}

</script>

<style lang="scss" scoped>
.wrap{
  padding-top: 46px;
  padding-bottom: 100px;
  .delete-button{
    height: 100%;
  }
  .item{
    display: flex;
    background-color: #fafafa;
    .van-checkbox {
      margin: 0 5px;
    }
    .van-card{
      flex: 1;
    }
  }
  .van-submit-bar {
    bottom: 50px;
    border-bottom:1px solid rgb(235, 235, 235);
  }
}
</style>
